package com.zengqingfa.rocketmq.transaction;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.io.UnsupportedEncodingException;


/**
 *
 * @fileName: TransactionConsumer
 * @author: zengqf3
 * @date: 2021-4-2 16:21
 * @description:
 */
public class TransactionConsumer {

    public static void main(String[] args) throws Exception {

        // 1、创建DefaultMQPushConsumer
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("demo_consumer_transaction_group");

        // 2、设置namesrv地址
        consumer.setNamesrvAddr("localhost:9876");

        // 3、设置消息拉取最大数
        consumer.setConsumeMessageBatchMaxSize(2);

        // 设置消息顺序
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);

        // 4、设置subscribe，这里是要读取订单主题信息
        // topic：指定消费的主题，subExpression：过滤规则
        consumer.subscribe("Topic_Transaction_Demo",
                "*");

        // 5、创建消息监听MessageListener
        consumer.registerMessageListener((MessageListenerConcurrently) (list, consumeConcurrentlyContext) -> {
            for (MessageExt msg : list) {
                try {
                    String topic = msg.getTopic();
                    String tags = msg.getTags();
                    String keys = msg.getKeys();
                    String body = new String(msg.getBody(), RemotingHelper.DEFAULT_CHARSET);
                    System.out.println("topic: " + topic + ", tags: " + tags + ", keys: " + keys + ", body: " + body);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
            }
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        });

        // 开启Consumer
        consumer.start();
    }
}
